package com.neusoft.bizcore.webauth.secret;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;

public class JsonLoginConfigurer<T extends JsonLoginConfigurer<T, B>, B extends HttpSecurityBuilder<B>>
        extends AbstractHttpConfigurer<T, B> {

    private final JsonUsernamePasswordAuthenticationFilter authFilter;

    public JsonLoginConfigurer() {
        this.authFilter = new JsonUsernamePasswordAuthenticationFilter();
    }

    @Override
    public void configure(final B http) throws Exception {
        //设置Filter使用的AuthenticationManager,这里取公共的即可
        this.authFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        //不将认证后的context放入session
        this.authFilter.setSessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy());
        final JsonUsernamePasswordAuthenticationFilter filter = this.postProcess(this.authFilter);
        //指定Filter的位置
        http.addFilterAfter(filter, LogoutFilter.class);
    }

    public JsonLoginConfigurer<T, B> loginSuccessHandler(final AuthenticationSuccessHandler authSuccessHandler) {
        this.authFilter.setAuthenticationSuccessHandler(authSuccessHandler);
        return this;
    }

    public JsonLoginConfigurer<T, B> loginFailureHandler(final AuthenticationFailureHandler authFailureHandler) {
        this.authFilter.setAuthenticationFailureHandler(authFailureHandler);
        return this;
    }

    public JsonLoginConfigurer<T, B> usernameParameter(final String usernameParameter) {
        this.authFilter.setUsernameParameter(usernameParameter);
        return this;
    }

    public JsonLoginConfigurer<T, B> passwordParameter(final String passwordParameter) {
        this.authFilter.setPasswordParameter(passwordParameter);
        return this;
    }

    public JsonLoginConfigurer<T, B> loginProcessesUrl(final String processesUrl) {
        this.authFilter.setFilterProcessesUrl(processesUrl);
        return this;
    }
}
